from openai import OpenAI


def generate_text(
        prompt: str,
        api_key: str,
        system_prompt: str,
        base_url: str = "https://ark.cn-beijing.volces.com/api/v3",
        model: str = "deepseek-v3-250324",
        temperature: float = 0.7,
        max_tokens: int = 1024,
) -> str:
    """
    使用 LLM 生成文本

    输入字符串，返回生成的文本字符串

    Args:
        prompt: 输入的提示文本
        api_key: API密钥

    Returns:
        生成的文本内容

    Raises:
        ValueError: 当 API 密钥为空时
        Exception: 当 API 调用失败时
    """
    if not api_key:
        raise ValueError("API密钥不能为空")

    # 初始化客户端
    client = OpenAI(
        base_url=base_url,
        api_key=api_key,
    )

    try:
        # 调用 API 生成文本
        completion = client.chat.completions.create(
            model=model,
            temperature=temperature,
            max_tokens=max_tokens,
            messages=[
                {"role": "system", "content": system_prompt},
                {"role": "user", "content": prompt},
                {"role": "assistant", "content": "prompt:"},
            ],
        )

        # 返回生成的文本
        return completion.choices[0].message.content

    except Exception as e:
        raise Exception(f"调用  API 失败: {e}")
